/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/*!
 * Ext JS Library 3.0.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
Ext.onReady(function(){

    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';

    var bd = Ext.getBody();
    var conid = '';

    var stops_store = new Ext.data.JsonStore({
        root: 'stops',
        totalProperty: 'total',
        idProperty: 'stopid',
        remoteSort: true,

        fields: [
            'stopid', 'name', 'description', 'latitude', 'longitude',
            {name: 'connections', type: 'int'}
        ],

        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: 'allStops.jsp'
        })
    });
    stops_store.setDefaultSort('name', 'asc');
    stops_store.load({params:{start:0, limit:100}});

    var time_store = new Ext.data.JsonStore({
        root: 'times',
        totalProperty: 'total',
        idProperty: 'time',
        fields: [
            'time', 'duration', 'desc'
        ],

        proxy: new Ext.data.HttpProxy({
            url: 'getDepartures.jsp'
        })
    });
    time_store.setDefaultSort('time', 'asc');

    var conn_store = new Ext.data.JsonStore({
        root: 'departures',
        totalProperty: 'total',
        idProperty: 'conid',
        fields: [
            'conid','stopid','sname', 'depid','dname', 'departures'
        ],
        proxy: new Ext.data.HttpProxy({
            url: 'getDepartures.jsp'
        })
    });

    
    conn_store.setDefaultSort('sname', 'asc')
    conn_store.load({params:{start:0, limit:25, id: aStop.sid, action:'conns'}});

    // pluggable renders
    function renderConnection(value, p, record){
        return String.format(
                '<div style="padding: 2px"><img vallign="bottom" src="/images/zoom.png" alt="View Deatails">' +
                '<b> {0} </b></div>',
                value );
    }
    
    function renderTime(value, p, record) {
        var dt = new Date(value);
        //Diplay as current time
        dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset() );
        return dt.format('H:i');
    }
    // the DefaultColumnModel expects this blob to define columns. It can be extended to provide
    // custom or reusable ColumnModels
    var conModel = new Ext.grid.ColumnModel([
        {id:'company',header: "Destination", width: 280, sortable: true, locked:false, dataIndex: 'dname', renderer: renderConnection},
    ]);



    var search = new Ext.form.ComboBox({
        store: stops_store,
        pageSize:15,
        displayField:'name',
        typeAhead: true,
        queryParam:'keyword',
        loadingText: 'Searching...',
        forceSelection: true,
        triggerAction: 'all',
        emptyText:'Select a connection...',
        selectOnFocus:true
    });


    var connWin = new Ext.Window({
        title: 'Select Connection',
        layout:'fit',
        width:400,
        height:100,
        modal:true,
        closeAction:'hide',
        plain: true,
        items: search,
        

        buttons: [{
            text:'Add',
            handler: function() {
                var selectedid = stops_store.getAt(search.selectedIndex).data.stopid;
                var selectname = stops_store.getAt(search.selectedIndex).data.name;
                //alert(aStop.sid + ', ' + aStop.name + ', ' + selectedid + ', ' + selectname );
                Ext.Ajax.request({
                        url:'saveConnection.jsp',
                        method: 'POST',
                        params: {sid:aStop.sid, sname: aStop.name, did: selectedid, dname:selectname },
                        success: function(responseObject) {
                            //Ext.Msg.alert(responseObject.responseText);
                            Ext.Msg.alert('Status','Saved');
                            connWin.hide();
                            conn_store.load({params:{start:0, limit:25, id: aStop.sid, action:'conns'}});
                            
                        },
                        failure: function() {
                            
                            Ext.Msg.alert('Status', 'Please try again later.');
                        }


                        })
                
            }
        },{
            text: 'Close',
            handler: function(){
                connWin.hide();
            }
        }]
    });

 var timeform = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden
        url:'save-form.php',
        frame:false,

        bodyStyle:'padding:5px 5px 0',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',

        items: [{
                fieldLabel: 'Description',
                name: 'desc',
                allowBlank:false
            }, new Ext.form.NumberField({
                fieldLabel: 'Duration',
                allowBlank:false,
                name: 'duration'
            }),
             new Ext.form.TimeField({
                allowBlank:false,
                fieldLabel: 'Departs',
                format:"H:i",
                name: 'time'
            })
        ],

        buttons: [{
            text: 'Save',
            handler: function() {
                //alert(aStop.sid + ', ' + aStop.name + ', ' + selectedid + ', ' + selectname );
               
                timeform.form.submit({
                url:'saveConnection.jsp?update='+conid,
                method: 'POST',
                waitMsg:'Saving Data...',
                success: function (form, action) {
                    Ext.MessageBox.alert('Message', 'Saved OK ');
                    //alert(action.response.responseText);
                },
                failure:function(form, action) {
                    Ext.MessageBox.alert('Message', 'Save failed <p>' + action.response.responseText);
                }
            });

            }

        },{
            text: 'Close',
            handler: function (){
                time_store.load({params:{start:0, limit:50, id:conid, action:'times'}});
                timeWin.hide();
            }
        }]
    });


    var timeWin = new Ext.Window({
        title: 'Create Departure',
        layout:'fit',
        width:400,
        height:200,
        modal:true,
        closeAction:'hide',
        plain: true,
        items: timeform


        
    });



/*
 *    Here is where we create the Form
 */
    var gridForm = new Ext.FormPanel({
        id: 'main-form',
        frame: true,
        labelAlign: 'left',
        title: aStop.name + ' connections',
        root: '0',
        bodyStyle:'padding:5px',
        width: 750,
        layout: 'column',    // Specifies that the items will now be arranged in columns
        /* bbar: new Ext.Toolbar({
            items:[
                    '-',{
                        text: '<div><img align="left" src="/ext/resources/images/default/dd/drop-add.gif" style="vertical-align:middle;" >' +
                            '&nbsp;<span style="border:0px solid black; vertical-align:middle; " > Add new</span></div>',
                        handler: function (){
                            //TODO
                            //alert(1);

                        }

                    }

               ]
            }), */
        items: [{
            columnWidth: 0.40,
            layout: 'fit',
            items: {
                xtype: 'grid',
                ds: conn_store,
                cm: conModel,
                sm: new Ext.grid.RowSelectionModel({
                    singleSelect: true,
                    listeners: {
                        rowselect: function(sm, row, rec) {
                            conid = rec.data.conid;
                            //alert(conid);
                            time_store.load({params:{start:0, limit:25, id:conid, action:'times'}});
                        }
                    }
                }),
                height: 350,
                title:'Connections',
                border: true,
                bbar: new Ext.Toolbar({

                    items:[
                        '-',{
                            text: '<div><img align="left" src="/ext/resources/images/default/dd/drop-add.gif" style="vertical-align:middle;" >' +
                                '&nbsp;<span style="border:0px solid black; vertical-align:middle; " > Add new</span></div>',
                            handler: function (){
                                connWin.show();

                            }

                        }

                   ]
                }),
                listeners: {
                    render: function(g) {
                        g.getSelectionModel().selectRow(0);
                    },
                    delay: 10 // Allow rows to be rendered.
                }
            }
        },{
            columnWidth: 0.6,
            
            defaults: {width: 400, border:false},    // Default config options for child items
            defaultType: 'textfield',
            bodyStyle: 'padding-left: 10px',
            items: [{
                xtype: 'grid',
                id: 'connections-grid',
                ds: time_store,
                       // grid columns
                columns:[{
                    //id: 'stop', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                    header: "Departs",
                    dataIndex: 'time',
                    width: 70,
                    renderer: renderTime,
                    sortable: true
                },{
                    header: "Duration",
                    dataIndex: 'duration',
                    width: 70,
                    align: 'center',
                    sortable: true
                },{
                    header: "Description",
                    dataIndex: 'desc',
                    width: 230,
                    align: 'left',
                    sortable: true
                }],
          
                height: 350,
                title:'Departure Times',
                border: true,

                bbar: new Ext.Toolbar({

                    items:[
                        '-',{
                            text: '<div><img align="left" src="/ext/resources/images/default/dd/drop-add.gif" style="vertical-align:middle;" >' +
                                '&nbsp;<span style="border:0px solid black; vertical-align:middle; " > Add new</span></div>',
                            handler: function (){

                                //alert(conid);
                                timeWin.show();

                            }

                        }

                   ]
                })

            }]
        }],
        renderTo: bd
    });

});


